﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using Wicresoft.Logger;
using Wicresoft.Message.Entity;

namespace Wicresoft.Message
{
    public static class SmtpHelper
    {
        /// <summary>
        /// 发送邮件，将邮件对象保存到数据库，等待发送
        /// </summary>
        /// <param name="subject">邮件主题</param>
        /// <param name="body">邮件内容，可以是HTML格式</param>
        /// <param name="from">邮件发送人，如ccs@alcatel-sbell.com.cn</param>
        /// <param name="to">邮件接收人，只能填写一个人，如miles@wicresoft.com</param>
        public static void SendEmail(string subject, string body, string from, string to)
        {
            SendEmail(subject, body, from, new string[] { to });
        }

        /// <summary>
        /// 发送邮件，将邮件对象保存到数据库，等待发送
        /// </summary>
        /// <param name="subject">邮件主题</param>
        /// <param name="body">邮件内容，可以是HTML格式</param>
        /// <param name="from">邮件发送人，如ccs@alcatel-sbell.com.cn</param>
        /// <param name="to">邮件接收人列表，可以填写多个人，如miles@wicresoft.com</param>
        /// <param name="cc">邮件抄送人列表，可以填写多个人，如miles@wicresoft.com</param>
        /// <param name="bcc">邮件暗送人列表，可以填写多个人，如miles@wicresoft.com</param>
        /// <param name="replyTo">邮件回复人列表，可以填写多个人，如miles@wicresoft.com</param>
        /// <param name="pri">邮件优先级</param>
        public static void SendEmail(string subject, string body, string from, string[] to, string[] cc = null, string[] bcc = null, string[] replyTo = null, MailPriority pri = MailPriority.Normal)
        {
            if (to == null)
                throw new ArgumentNullException("Email To cannot be null");
            if (cc == null)
                cc = new string[] { };
            if (bcc == null)
                bcc = new string[] { };
            if (replyTo == null)
                replyTo = new string[] { };

            using (var dc = new EmailContext())
            {
                var email = new Email
                {
                    CreatedTime = DateTime.Now,
                    Subject = subject,
                    Body = body,
                    From = from,
                    To = String.Join(";", to.Where(p => CheckEmailFormat(p))),
                    Cc = String.Join(";", cc.Where(p => CheckEmailFormat(p))),
                    Bcc = String.Join(";", bcc.Where(p => CheckEmailFormat(p))),
                    ReplyTo = String.Join(";", replyTo.Where(p => CheckEmailFormat(p))),
                    Priority = (int)pri,
                };

                dc.Emails.Add(email);

                try
                {
                    dc.SaveChanges();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException e)
                {
                    Log.Exception("SmtpHelper", e);

                    foreach (var err in e.EntityValidationErrors)
                    {
                        foreach (var er in err.ValidationErrors)
                        {
                            Log.Debug("SmtpHelper", "ValidationErrors: {0}, {1}", er.PropertyName, er.ErrorMessage);
                        }
                    }
                }
            }
        }

        private static bool CheckEmailFormat(string email)
        {
            return !String.IsNullOrWhiteSpace(email) &&
                Regex.IsMatch(email, @"[\.a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+");
        }
    }
}
